const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const schedule = require('node-schedule');
const screenshot = require('screenshot-desktop');
const moment = require('moment');
const { OpenAI } = require('openai');
const sharp = require('sharp');
const dotenv = require('dotenv');

// 加载环境变量
dotenv.config();

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));

// 确保必要的目录存在
const STORAGE_DIR = path.join(__dirname, 'storage');
const SCREENSHOTS_DIR = path.join(STORAGE_DIR, 'screenshots');
const JOURNALS_DIR = path.join(STORAGE_DIR, 'journals');
const CONFIG_FILE = path.join(STORAGE_DIR, 'config.json');

[STORAGE_DIR, SCREENSHOTS_DIR, JOURNALS_DIR].forEach(dir => {
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
});

// 全局变量
let isRecording = false;
let screenshotJob = null;
let journalJob = null;
let settings = {
  screenshotInterval: 1, // 分钟
  journalInterval: 6,    // 分钟
  historyCount: 0        // 附带历史条目数
};

// 加载配置
function loadConfig() {
  try {
    if (fs.existsSync(CONFIG_FILE)) {
      const configData = fs.readFileSync(CONFIG_FILE, 'utf8');
      const savedSettings = JSON.parse(configData);
      settings = { ...settings, ...savedSettings };
      console.log('配置已从本地加载');
    } else {
      saveConfig();
      console.log('创建了默认配置文件');
    }
  } catch (error) {
    console.error('加载配置失败:', error);
  }
}

// 保存配置
function saveConfig() {
  try {
    fs.writeFileSync(CONFIG_FILE, JSON.stringify(settings, null, 2));
    console.log('配置已保存到本地');
  } catch (error) {
    console.error('保存配置失败:', error);
  }
}

// 加载配置
loadConfig();

// OpenAI 客户端
let openai;
try {
  openai = new OpenAI({
    apiKey: process.env.OPENAI_API_KEY,
    baseURL: process.env.OPENAI_BASE_URL,
  });
} catch (error) {
  console.error('OpenAI 初始化失败:', error);
}

// 路由
app.get('/api/status', (req, res) => {
  res.json({
    isRecording,
    settings
  });
});

app.post('/api/settings', (req, res) => {
  const { screenshotInterval, journalInterval, historyCount } = req.body;
  
  // 验证参数
  if (screenshotInterval && (screenshotInterval < 1 || screenshotInterval > 60)) {
    return res.status(400).json({ error: '截图间隔必须在1-60分钟之间' });
  }
  
  if (journalInterval && (journalInterval < 1 || journalInterval > 240)) {
    return res.status(400).json({ error: '手账生成间隔必须在1-240分钟之间' });
  }
  
  if (historyCount !== undefined && (historyCount < 0 || historyCount > 10)) {
    return res.status(400).json({ error: '历史附带条目数必须在0-10之间' });
  }
  
  if (screenshotInterval && journalInterval && screenshotInterval > journalInterval) {
    return res.status(400).json({ error: '截图间隔必须小于或等于手账间隔' });
  }
  
  // 更新设置
  if (screenshotInterval) settings.screenshotInterval = screenshotInterval;
  if (journalInterval) settings.journalInterval = journalInterval;
  if (historyCount !== undefined) settings.historyCount = historyCount;
  
  // 保存配置到本地文件
  saveConfig();
  
  // 如果正在记录，重新调度任务
  if (isRecording) {
    stopRecording();
    startRecording();
  }
  
  res.json({ success: true, settings });
});

app.post('/api/control', (req, res) => {
  const { action } = req.body;
  
  if (action === 'start') {
    if (!isRecording) {
      startRecording();
      res.json({ success: true, message: '记录已开始' });
    } else {
      res.json({ success: false, message: '已经在记录中' });
    }
  } else if (action === 'stop') {
    if (isRecording) {
      stopRecording();
      res.json({ success: true, message: '记录已停止' });
    } else {
      res.json({ success: false, message: '当前没有记录进行' });
    }
  } else {
    res.status(400).json({ error: '无效的操作' });
  }
});

app.get('/api/journals', (req, res) => {
  const { startDate, endDate, minDuration, maxDuration, type } = req.query;
  
  fs.readdir(JOURNALS_DIR, (err, files) => {
    if (err) {
      return res.status(500).json({ error: '无法读取手账目录' });
    }
    
    // 只处理JSON文件
    const journalFiles = files.filter(file => file.endsWith('.json'));
    
    // 读取所有手账文件
    Promise.all(journalFiles.map(file => {
      return new Promise((resolve, reject) => {
        fs.readFile(path.join(JOURNALS_DIR, file), 'utf8', (err, data) => {
          if (err) return reject(err);
          try {
            const journal = JSON.parse(data);
            resolve(journal);
          } catch (e) {
            reject(e);
          }
        });
      });
    }))
    .then(journals => {
      // 应用筛选条件
      let filteredJournals = journals;
      
      if (startDate) {
        const start = new Date(startDate);
        filteredJournals = filteredJournals.filter(j => new Date(j.timestamp) >= start);
      }
      
      if (endDate) {
        const end = new Date(endDate);
        filteredJournals = filteredJournals.filter(j => new Date(j.timestamp) <= end);
      }
      
      if (minDuration) {
        filteredJournals = filteredJournals.filter(j => j.duration >= parseInt(minDuration));
      }
      
      if (maxDuration) {
        filteredJournals = filteredJournals.filter(j => j.duration <= parseInt(maxDuration));
      }
      
      if (type) {
        filteredJournals = filteredJournals.filter(j => j.type === type);
      }
      
      // 按时间倒序排列
      filteredJournals.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
      
      res.json(filteredJournals);
    })
    .catch(error => {
      res.status(500).json({ error: '读取手账数据失败', details: error.message });
    });
  });
});

app.get('/api/journal/:id', (req, res) => {
  const journalId = req.params.id;
  const journalPath = path.join(JOURNALS_DIR, `${journalId}.json`);
  
  fs.readFile(journalPath, 'utf8', (err, data) => {
    if (err) {
      return res.status(404).json({ error: '手账不存在' });
    }
    
    try {
      const journal = JSON.parse(data);
      res.json(journal);
    } catch (e) {
      res.status(500).json({ error: '手账数据格式错误' });
    }
  });
});

// 辅助函数
async function takeScreenshot() {
  try {
    const timestamp = moment().format('YYYY-MM-DD_HH-mm-ss');
    
    // 获取所有屏幕的截图
    const screenshots = await screenshot.all();
    console.log(`捕获了 ${screenshots.length} 个屏幕的截图`);
    
    // 保存每个屏幕的截图
    const filepaths = [];
    for (let i = 0; i < screenshots.length; i++) {
      const filename = `${timestamp}_screen${i+1}.jpg`;
      const filepath = path.join(SCREENSHOTS_DIR, filename);
      
      // 将截图缓冲区转换为JPG格式并写入文件
      await sharp(screenshots[i])
        .jpeg({
          quality: 85,
          chromaSubsampling: '4:4:4'
        })
        .toFile(filepath);
      console.log(`截图已保存: ${filename}`);
      filepaths.push(filepath);
    }
    
    return filepaths;
  } catch (error) {
    console.error('截图失败:', error);
    return null;
  }
}

async function generateJournal() {
  try {
    // 获取最近的截图
    const files = fs.readdirSync(SCREENSHOTS_DIR)
      .filter(file => file.endsWith('.jpg'))
      .sort((a, b) => {
        // 按文件名（时间戳）排序
        return b.localeCompare(a);
      });
    
    if (files.length === 0) {
      console.log('没有可用的截图');
      return;
    }
    
    // 计算应该处理的截图数量（基于间隔）
    const recentFiles = files
    
    console.log(`处理 ${recentFiles.length} 张最近的截图`);
    
    // 获取历史手账（如果需要）
    let recentJournals = [];
    if (settings.historyCount > 0) {
      const journalFiles = fs.readdirSync(JOURNALS_DIR)
        .filter(file => file.endsWith('.json'))
        .sort((a, b) => b.localeCompare(a))
        .slice(0, settings.historyCount);
      
      recentJournals = journalFiles.map(file => {
        const data = fs.readFileSync(path.join(JOURNALS_DIR, file), 'utf8');
        return JSON.parse(data);
      });
    }
    
    // 准备AI分析的上下文
    let prompt = "请分析以下工作时候的电脑屏幕截图，生成一个结构化的工作日志条目。使用markdown格式输出。";
    prompt += "\n\n截图时间范围: " + moment().subtract(settings.journalInterval, 'minutes').format('HH:mm:ss') + " 至 " + moment().format('HH:mm:ss');
    
    if (recentJournals.length > 0) {
      prompt += "\n\n最近的工作记录:";
      recentJournals.forEach((journal, index) => {
        prompt += `\n${index + 1}. ${journal.timestamp}: ${journal.summary}`;
      });
    }
    
    // 调用OpenAI API
    if (!openai) {
      console.error('OpenAI 客户端未初始化');
      return;
    }
    
    console.log('AI分析中...');

    const response = await openai.chat.completions.create({
      model: "gpt-4o",
      messages: [
        {
          role: "user",
          content: [
            { type: "text", text: prompt },
            ...recentFiles.map(file => ({
              type: "image_url",
              image_url: {
                url: `data:image/jpeg;base64,${fs.readFileSync(path.join(SCREENSHOTS_DIR, file)).toString('base64')}`,
              }
            }))
          ],
        },
      ],
      max_tokens: 1000,
    });

    console.log('AI分析完成');
    
    // 解析AI响应
    const aiResponse = response.choices[0].message.content;
    
    // 创建手账条目
    const journalEntry = {
      id: moment().format('YYYYMMDDHHmmss'),
      timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
      duration: settings.journalInterval,
      screenshots: recentFiles,
      summary: aiResponse,
      type: detectWorkType(aiResponse) // 可以基于AI响应推断工作类型
    };
    
    // 保存手账
    const journalPath = path.join(JOURNALS_DIR, `${journalEntry.id}.json`);
    fs.writeFileSync(journalPath, JSON.stringify(journalEntry, null, 2));
    
    console.log(`手账已生成: ${journalEntry.id}`);
    
    // 清理已处理的截图
    recentFiles.forEach(file => {
      fs.unlinkSync(path.join(SCREENSHOTS_DIR, file));
      console.log(`已删除截图: ${file}`);
    });
    
  } catch (error) {
    console.error('生成手账失败:', error);
  }
}

function detectWorkType(summary) {
  // 简单的工作类型检测逻辑
  const types = {
    '编程': ['代码', '编程', '开发', 'bug', '调试', '函数', '变量', '类', '方法'],
    '文档': ['文档', '写作', '报告', '文章', '笔记', '记录'],
    '会议': ['会议', '讨论', '沟通', '交流', '演示', '展示', '分享'],
    '设计': ['设计', 'UI', 'UX', '界面', '原型', '图形', '布局'],
    '研究': ['研究', '分析', '调查', '探索', '学习', '阅读'],
    '其他': []
  };
  
  for (const [type, keywords] of Object.entries(types)) {
    if (keywords.some(keyword => summary.includes(keyword))) {
      return type;
    }
  }
  
  return '其他';
}

function startRecording() {
  if (isRecording) return;
  
  isRecording = true;
  
  // 调度截图任务
  screenshotJob = schedule.scheduleJob(`*/${settings.screenshotInterval} * * * *`, takeScreenshot);
  
  // 调度手账生成任务
  journalJob = schedule.scheduleJob(`*/${settings.journalInterval} * * * *`, generateJournal);
  
  console.log('记录已开始');
  
  // 立即执行一次截图
  takeScreenshot();
}

function stopRecording() {
  if (!isRecording) return;
  
  isRecording = false;
  
  // 取消调度任务
  if (screenshotJob) {
    screenshotJob.cancel();
    screenshotJob = null;
  }
  
  if (journalJob) {
    journalJob.cancel();
    journalJob = null;
  }
  
  console.log('记录已停止');
}

// 启动服务器
app.listen(PORT, () => {
  console.log(`Techo 服务器运行在 http://localhost:${PORT}`);
});